<template>
  <div class="user">
    <van-dialog @confirm="handlePassword" v-model:show="showPassword" title="标题" show-cancel-button>
      <div class="mb-2 mt-3  text-center">
        <input v-model="oldPassword" class="showInp border ps-2 rounded" type="password" placeholder="请输入旧密码">
      </div>
      <div class="mb-2 text-center">
        <input v-model="password1" class=" showInp border ps-2 rounded" type="password" placeholder="请输入新密码">
      </div>
      <div class="mb-3 text-center">
        <input v-model="password2" class=" showInp border ps-2 rounded" type="password" placeholder="再次输入新密码">
      </div>
    </van-dialog>
    <div class="container">
      <div class="user-info">
        <div class="user-header d-flex justify-content-around align-items-center">
          <h3 @click="isOpenFn(0)" :class="num == 0 ? 'active' : ''">个人信息</h3>
          <h3 @click="isOpenFn(1)" :class="num == 1 ? 'active' : ''">评论中心</h3>
        </div>
        <div :class="['user-data', num == 0 ? '' : 'active']">
          <div class="user-info-img">
            <img :src="imUrl" alt="">
          </div>
          <div class="box">
            <div class="user-info-data p-1 mt-2">
              账号:<span style="color: #666;">{{ userData.account }}</span>
              <button @click="logoutFn" style="padding: 0 2px; font-size: 12px;"
                class="btn btn-outline-danger ms-2">退出登录</button>
              <button @click="medityPass" style="padding: 0 2px; font-size: 12px;"
                class="btn btn-outline-warning ms-2">修改密码</button>
            </div>
            <div class="user-info-data p-1">
              注册时间:<span style="color: #666;">{{ formatDate(userData.createAt) }}</span>
            </div>
            <div class="user-info-data p-1 mt-1">
              用户昵称:
              <input v-model="newUsername" style="margin-left: 4px;" type="text" class="text"
                :placeholder="userData.username">
            </div>
            <div class="user-info-data p-1">
              性别:<span class="me-1">男</span>
              <input v-model="check" type="radio" name="sex" value="男">
              <span class="ms-1 me-1">女</span>
              <input v-model="check" type="radio" name="sex" value="女">
              <span class="ms-1 me-1">不告诉你</span>
              <input v-model="check" type="radio" name="sex" value="未知">
            </div>
            <div class="p-1 title d-flex">
              个性标签:
              <div class="ps-1">
                <textarea v-model="newTag" style="color:#666;" class="text rounded" placeholder="来设置个性标签吧~~"></textarea>
              </div>
            </div>
            <div class=" d-flex justify-content-center">
              <div @click="submitFn" class="my-btn btn mt-3">设置</div>
            </div>
          </div>
        </div>
        <div :class="['user-comment text-center', num == 1 ? '' : 'active']">
          <h6 class="pt-3">我的随笔评论</h6>
          <ul v-if="commentList.length > 0" class="user-list">
            <li v-for="item in commentList" :key="item.id"
              class="user-item mt-2  d-flex justify-content-between align-items-center">
              <div class="left">
                <div class="text ellipsis">
                  {{ item.comment }}
                </div>
                <div class="time">
                  时间： {{ item.createAt || '未知时间' }}
                </div>
              </div>
              <div class="right">
                <button @click="modifyClick(item.id)" type="button" class="btn btn-sm me-2 btn-outline-secondary">
                  修改
                </button>
                <button @click="clickRemove(item.id)" type="button" class="btn btn-sm btn-outline-danger ">
                  删除
                </button>
              </div>
            </li>

          </ul>
          <van-pagination v-if="commentList.length > 0" class="myPage mt-2" v-model="page" @change="onPageChange"
            :page-count="pageTotal" mode="simple" />

          <div v-if="commentList.length == 0" class="message">
            您还没有评论，快去发表吧~~
          </div>
        </div>
      </div>

    </div>
    <van-dialog @confirm="handleConfirm" v-model:show="show" title="修改评论" show-cancel-button>
      <div class="p-2">
        <textarea v-model="newText" class="p-2 rounded" style="width: 100%;height: 100px; font-size: 14px;"
          placeholder="请输入评论"></textarea>
      </div>
    </van-dialog>
  </div>
</template>

<script setup lang="ts">
import { modifyUserInfo, modifyPassword, getListByUser, modifyNoteComment, removeNoteComment, host } from '@/api/index';
import { Dialog } from "vant";
import { ElMessage } from 'element-plus'
import defaultUserImage from '@/static/imgs/images/morenuser.png';
import { useCounterStore } from "@/stores/counter"
import { ref } from 'vue';
import { useRouter } from 'vue-router';
const router = useRouter();

const show = ref<boolean>(false);
const showPassword = ref<boolean>(false);
const newText = ref<string>('');
// 调用pinia
const counter = useCounterStore();
const num = ref<number>(0);

const page = ref<number>(1);
const size = ref<number>(4);
const pageTotal = ref<number>(0);
interface listItem {
  id: number;
  user_id: number;
  note_id: number;
  comment: string;
  createAt: string;
  username: string;
  imgUrl: string;
}

const commentList = ref<listItem[]>([]);

// 用户数据
let userData = counter.userData;
// console.log(userData)

// 用户头像地址
let imUrl = userData.imgUrl ? host + userData.imgUrl : defaultUserImage;
// console.log(imUrl)


// 个性签名
const newTag = ref<string>('');
newTag.value = userData.tag;
// 用户昵称
const newUsername = ref<string>('');
// 性别
const check = ref<string>('');
check.value = userData.gender == '' ? '未知' : userData.gender;

const oldPassword = ref<string>('');
// 密码
const password1 = ref<string>('');
const password2 = ref<string>('');

// 修改密码的弹出框
const medityPass = async () => {
  showPassword.value = true;
}

// 确认后修改密码
const handlePassword = async () => {
  // console.log(111)
  if (oldPassword.value == '' || password1.value == '' || password2.value == '') {
    ElMessage({
      showClose: true,
      message: '你还没写呢~~',
      type: 'warning',
      offset: 100,
      plain: true
    })
    return false
  }
  if (password1.value != password2.value) {
    ElMessage({
      showClose: true,
      message: '密码不一致~~',
      type: 'warning',
      offset: 100,
      plain: true
    })
    return false
  }
  await modifyPassword({ oldPassword: oldPassword.value, newPassword: password1.value, id: userData.id })
    .then(
      res => {
        if (res.data.code == 200) {
          ElMessage({
            showClose: true,
            message: '修改密码成功~~',
            type: 'success',
            offset: 100,
            plain: true
          })
          foo()
          setTimeout(() => {
            ElMessage({
              showClose: true,
              message: '请重新登录~~',
              offset: 100,
              plain: true
            })
            router.push('/login')
          }, 1000)
        } else {
          ElMessage({
            showClose: true,
            message: res.data.msg,
            type: 'warning',
            offset: 100,
            plain: true
          })
        }
      }
    ).catch(() => {
      ElMessage({
        showClose: true,
        message: '修改密码失败~~',
        type: 'warning',
        offset: 100,
        plain: true
      })
    })
}
const foo = () => {
  localStorage.removeItem('TTOO');
  counter.userData = {
    id: -1,
    username: '',
    account: '',
    imgUrl: '',
    createAt: '',
    tag: '',
    gender: '',
  };
  userData = counter.userData;
  imUrl = defaultUserImage;
}
// 点击退出登录
const logoutFn = () => {
  Dialog.confirm({
    title: '提示',
    message: '您确定要退出登录吗？',
  })
    .then(() => {
      foo()
      ElMessage({
        showClose: true,
        message: '退出登录成功~~',
        type: 'success',
        offset: 100,
        plain: true,
      })
      // 跳转到首页
      setTimeout(() => {
        router.push('/');
      }, 1000);
    })
    .catch(() => { });

}

// 控制tab显示隐藏
const isOpenFn = (value: number) => {
  num.value = value;
}

const submitFn = async () => {
  // console.log(check.value)
  // console.log(newUsername.value)
  // console.log(newTag.value)
  if (newUsername.value == '' && newTag.value == '' && check.value == '') {
    ElMessage({
      showClose: true,
      message: '请填写完整信息~~',
      type: 'warning',
      offset: 100,
      plain: true,
    })
    return false
  }
  if (newUsername.value.trim() == '') {
    newUsername.value = userData.username;
  }
  if (newTag.value.trim() == '') {
    newTag.value = userData.tag;
  }
  if (check.value == '') {
    check.value = userData.gender;
  }
  await modifyUserInfo({
    id: userData.id,
    username: newUsername.value,
    tag: newTag.value,
    gender: check.value,
    imgUrl: userData.imgUrl,
  }).then(
    res => {
      if (res.data.code == 200) {
        ElMessage({
          showClose: true,
          message: '设置成功~~',
          type: 'success',
          offset: 100,
          plain: true,
        })
        userData.username = newUsername.value;
        userData.tag = newTag.value;
        userData.gender = check.value;
        // console.log(333, res.data)
      } else {
        ElMessage({
          showClose: true,
          message: '设置失败~~',
          type: 'warning',
          offset: 100,
          plain: true,
        })
      }
    }
  ).catch(() => {
    ElMessage({
      showClose: true,
      plain: true,
      message: '设置失败~~',
      type: 'warning',
      offset: 100,
    })
  })
}

// 格式化时间
const formatDate = (date: string) => {
  const time = new Date(date);
  return time.toLocaleString();
}
// formatDate(userData.createAt)

// 获取用户的评论数据
const getListByUserFn = async () => {
  const user_id = userData.id
  const page_num = page.value;
  const page_size = size.value;
  await getListByUser({ user_id, page_num, page_size }).then(
    res => {
      commentList.value = res.data.result
      pageTotal.value = Math.ceil(res.data.total / page_size)
      // console.log(res.data)
    },
    err => {
      console.log(err)
    }
  )
}
getListByUserFn()



// 分页变化处理函数
const onPageChange = (newPage: number) => {
  page.value = newPage;
  getListByUserFn();
}

const id = ref<number>(0)
const modifyClick = (ID: number) => {
  show.value = true;
  id.value = ID
}
// 修改评论
const modifyNoteCommentFn = async (comment: string, id: number) => {
  await modifyNoteComment({ comment, id }).then(
    res => {
      // console.log("修改评论", res.data)
      if (res.data.code == 200) {
        ElMessage({
          showClose: true,
          message: '修改评论成功~~',
          type: 'success',
          offset: 100,
          plain: true,
        })
        getListByUserFn()
        newText.value = ''
      }
    },
    err => {
      console.log(err)
    }
  )
}
// 确认后执行的函数
const handleConfirm = async () => {
  const comment = newText.value
  if (!comment) {
    ElMessage({
      showClose: true,
      message: '你还没写呢~~',
      type: 'warning',
      offset: 100,
      plain: true,
    })
    return
  }
  // console.log('newText', newText.value)
  // console.log('id', id.value)
  await modifyNoteCommentFn(comment, id.value)
}

const clickRemove = async (value: number) => {
  Dialog.confirm({
    title: '删除评论',
    message:
      '您确定要删除吗？',
  })
    .then(async () => {
      await removeNoteCommentFn(value)
    })
    .catch(() => {
      // on cancel
    });

}

// 删除评论
const removeNoteCommentFn = async (value: number) => {
  const id = value
  await removeNoteComment({ id }).then(
    res => {
      if (res.data.code == 200) {
        ElMessage({
          showClose: true,
          message: '删除成功~~',
          type: 'success',
          offset: 100,
          plain: true,
        })
        // console.log(res.data)
        getListByUserFn()
      }
    },
    err => {
      console.log(err)
    }
  )
}
</script>

<style lang="less" scoped>
@import "@/static/css/common.less";

@keyframes show {
  0% {
    opacity: 0.65;
    transform: translateY(-3%);
  }

  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.showInp {
  width: 80%;
  font-size: 16px;
  border: 1px solid #ccc !important;
}

.user {
  width: 100%;
  height: 100%;
  background-image: url(../static/imgs/images/home-bg5.jpg);
  background-size: cover;
  animation: show 1s ease-in-out;
  padding-bottom: 50px;

  .container {
    width: 70%;
    height: 500px;
    position: absolute !important;
    left: 50%;
    top: 52%;
    transform: translate(-50%, -50%);
  }

  .user-info {
    border-radius: 20px;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 0.8);
    padding: 20px;
    // text-align: center;

    h3 {
      font-size: 23px;
      cursor: pointer;

      &.active {
        color: #FFA500;
      }
    }

    .user-info-img {
      width: 100px;
      height: 100px;
      margin: 0 auto;
      // padding: 40px 0;

      img {
        width: 100%;
        height: 100px;
        border-radius: 50%;
        background-color: #fff;
      }
    }

    .title {

      .text {
        width: 200px;
        font-size: 13px;
        padding: 5px;
        border: none;
        background-color: rgba(255, 251, 251, 0.7);
      }
    }

    .my-btn {
      background-color: #fca80b;
    }
  }

  .user-data,
  .user-comment {
    transition: opacity 1s ease-in-out;
    opacity: 1;
    transform: translateY(0);
    max-height: 1000px;
    /* 设置一个足够大的最大高度 */
    overflow: hidden;

    &.active {
      opacity: 0;
      transform: translateY(-20px);
      max-height: 0;
      padding: 0;
      margin: 0;
    }
  }

  .user-data {
    margin-top: 20px;
  }

  .box {
    // background-color: red;
    width: 285px;
    margin: 0 auto;

    .user-info-data {
      width: 100%;
      font-size: 18px;
      margin-bottom: 5px;

      span {
        font-size: 13px;
        margin-left: 10px;
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
        border: none;
        background-color: rgba(255, 251, 251, 0.7);
        border-radius: 3px;
        padding-left: 5px;
        font-size: 14px;
      }

      .inp {
        margin-left: 87px;
      }
    }
  }


}

.user-comment {
  :deep(.van-pagination__item) {
    width: 60px !important;
    color: #FFA500 !important;
    border-radius: 5px !important;
    flex: inherit !important;
  }

  .message {
    width: 100%;
    padding-top: 100px;
    color: #767575;
  }
}

.user-comment .user-list {
  width: 100%;
  height: 344px;

  .user-item {
    width: 100%;
    height: 80px;
    // background: red;
    // background-color: rgba(247, 173, 36, 0.7);
    border-bottom: 1px solid rgba(247, 173, 36, 0.7);

    .left {
      text-align: start;
      width: calc(100% - 110px);

      .text {
        width: 100%;
        // background-color: #fff;
        padding: 5px 10px;
        color: #000;
        font-size: 13px;
      }

      .time {
        font-size: 10px;
        color: #706c6c;
        margin-top: 5px;
        padding-left: 10px;
      }
    }
  }
}



@media (max-width: 768px) {
  .container {
    width: 100% !important;
  }
}
</style>
